package algorithm.leetcode;

/**
 * @program: util
 * @description:不能用 * / % 求除法
 * @author: zhouliangliang
 * @create: 2021-04-16 10:59
 **/
public class Divide {

    //minus one by one
    private int divide1(int dividend, int divisor) {
        boolean sign = false;
        //都是整数或者都是负数
        if((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
            sign = true;
        }


        if(Math.abs(dividend) < Math.abs(divisor)) {
            return 0;
        }

        int i = 0;
        int value = Math.abs(dividend) - Math.abs(divisor);
        while (value > 0) {
            i++;
            value = Math.abs(value) - Math.abs(divisor);
        }

        if(sign == false) {
            return -i;
        } else {
            return i;
        }
    }


    //minus multiple 但是使用了乘法
    private int divide2(int dividend, int divisor) {
        boolean sign = false;
        //都是整数或者都是负数
        if((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
            sign = true;
        }

        int posDividend = Math.abs(dividend);
        int posDivisor = Math.abs(divisor);


        if(posDividend < posDivisor) {
            return 0;
        }

        int i = 0; //商
        int j = 0;
        int poor = posDividend - (posDivisor << pow(j));
        while (poor >= 0) {
            i = i + (1 << pow(j));
            poor = poor - (posDivisor << pow(j));
            j = j+1;
            if(poor < (posDivisor << pow(j))) {
                j = 0;
            }
        }


        if(sign == false) {
            return -i;
        } else {
            return i;
        }
    }

    private int pow(int j) {
        return j;
//        return Double.valueOf(Math.pow(2, j)).intValue();
    }



    public static void main(String[] args) {
//        System.out.println(new Divide().divide1(10, -13));
//        System.out.println(10/-13);
        System.out.println(new Divide().divide2(1001, 3));
//        System.out.println(3<<0);
//        System.out.println(3<<1);
//        System.out.println(6<<3);

//        System.out.println(1 << 2);
//        System.out.println(Math.pow(2,2));

    }
}
